public class Solution2 {
    public ListNode reverseKGroup(ListNode head, int k) {
        // 1. 先求出需要逆序多少组
        int n = 0;
        ListNode newHead = new ListNode();
        ListNode tmp = head;
        while(tmp != null) {
            tmp = tmp.next;
            n++;
        }
        n /= k;

        // 2. 重复 n 次 ： 长度为 k 的链表逆序
        ListNode cur = head;
        ListNode prev = newHead;
        ListNode next = head;
        for(int i = 0; i < n; i++) {
            tmp = cur;
            for(int j = 0; j < k; j++) {
                next = cur.next;
                cur.next = prev.next;
                prev.next = cur;
                cur = next;
            }
            prev = tmp;
        }

        // 3. 把最后的链表合并
        if(cur != null) {
            prev.next = cur;
        }
        return newHead.next;
    }
}
